﻿<script setup lang="ts">
import Vditor from 'vditor'
import 'vditor/dist/index.css'
import { onMountedOrActivated } from '@/hooks/onMountedOrActivated'
import { storeToRefs } from 'pinia'
import { useSystemConfigStore } from '@/store/storage/systemConfigStore'
import { loadEnv } from '^/index'
import { transformI18n } from '@/plugins/i18n'
const systemConfigStore = useSystemConfigStore()
const { systemConfig, language } = storeToRefs(systemConfigStore)
const { VITE_BASE_API_PATH, VITE_PUBLIC_PATH } = loadEnv()

const getTheme = (
  isLight: boolean,
  themeMode: 'default' | 'content' | 'code' = 'default'
) => {
  const isDark = !isLight
  switch (themeMode) {
    case 'default':
      return isDark ? 'dark' : 'classic'
    case 'content':
      return isDark ? 'dark' : 'light'
    case 'code':
      return isDark ? 'dracula' : 'github'
  }
}

type Lang = 'zh_CN' | 'zh_TW' | 'en_US' | undefined
const props = defineProps({
  height: { type: Number, default: 360 },
  value: { type: String, default: '' }
})
const emits = defineEmits(['change', 'get', 'update:value'])

const valueRef = ref(props.value || '')

const vditor = ref(null)
watch(
  () => systemConfig.value.isLight,
  (val) => {
    vditor.value.setTheme(getTheme(val) as any, getTheme(val, 'content'), getTheme(val, 'code'))
  }
)
watch(
  () => language.value,
  () => {
    destroy()
    initVditor()
  }
)

watch(
  () => props.value,
  (v) => {
    if (v !== valueRef.value) {
      vditor.value.setValue(v)
    }
    valueRef.value = v
  }
)

const getCurrentLang = computed((): 'zh_CN' | 'zh_TW' | 'en_US' => {
  let lang: Lang
  switch (language.value) {
    case 'en':
      lang = 'en_US'
      break
    case 'zh_tw':
      lang = 'zh_TW'
      break
    default:
      lang = 'zh_CN'
  }
  return lang
})
const initVditor = () => {
  const bindValue = { ...props }
  vditor.value = new Vditor('vditor', {
    cdn: VITE_PUBLIC_PATH + 'vditor',
    theme: getTheme(systemConfig.value.isLight) as any,
    lang: getCurrentLang.value,
    mode: 'sv',
    minHeight: 500,
    fullscreen: {
      index: 2048
    },
    preview: {
      theme: {
        // 设置内容主题
        current: getTheme(systemConfig.value.isLight, 'content')
      },
      actions: [],
      hljs: {
        style: getTheme(systemConfig.value.isLight, 'code'),
        lineNumber: true
      }
    },
    counter: {
      enable: true
    },
    icon: 'ant',
    toolbar: [
      'undo',
      'redo',
      '|',
      'headings',
      'bold',
      'italic',
      'strike',
      'link',
      '|',
      'list',
      'ordered-list',
      'check',
      'outdent',
      'indent',
      '|',
      'quote',
      'line',
      'code',
      'inline-code',
      'insert-before',
      'insert-after',
      'emoji',
      '|',
      'upload',
      'table',
      '|',
      'fullscreen',
      'edit-mode',
      'export',
      'preview',
      'help'
      // {
      //   name: 'more',
      //   toolbar: [
      //     // 'both',
      //     // 'code-theme',
      //     // 'content-theme',
      //     'export',
      //     'outline',
      //     'preview',
      //     // 'devtools',
      //     // 'info',
      //     'help'
      //   ]
      // }
    ],
    input: (v) => {
      valueRef.value = v
      emits('update:value', v)
      emits('change', v)
    },
    after: () => {
      vditor.value.setValue(valueRef.value)
    },
    upload: {
      accept: 'image/*',
      multiple: false,
      filename(name) {
        return name
          .replace(/[^(a-zA-Z0-9\u4e00-\u9fa5\.)]/g, '')
          .replace(/[\?\\/:|<>\*\[\]\(\)\$%\{\}@~]/g, '')
          .replace('/\\s/g', '')
      },
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      max: 2 * 1024 * 1024, // 上传图片的大小
      format: (files, result) => {
        const uploadObj = JSON.parse(result)
        console.log(uploadObj)
        const fileName = uploadObj.data.name
        if (uploadObj.code === 200) {
          return JSON.stringify({
            msg: uploadObj.info,
            code: uploadObj.code,
            data: {
              errFiles: [],
              succMap: {
                [fileName]: uploadObj.data.url
              }
            }
          })
        } else {
          console.log(uploadObj.info + transformI18n('errors.上传失败了', true))
        }
      },
      url: VITE_BASE_API_PATH + '/uploadFile',
      linkToImgUrl: VITE_BASE_API_PATH + '/uploadFile',
      // 粘贴图片回显处理，如果有图片加了防盗链，则让后台代理替换成自己的图片
      linkToImgFormat(files) {
        const resData = JSON.parse(files)
        const code = resData.code
        const msg = resData.info
        const data = resData.data
        // 上传图片请求状态
        if (code === 200) {
          const succ = {}
          succ[data.name] = data.url
          // 图片回显
          return JSON.stringify({
            msg,
            code,
            data: {
              errFiles: [],
              succMap: succ
            }
          })
        } else {
          console.log(msg + transformI18n('errors.上传失败了', true))
        }
      }
    },
    blur: () => {
      // unref(vditorRef)?.setValue(props.value);
    },
    ...bindValue,
    cache: {
      enable: false
    }
  })
}

function destroy() {
  if (!vditor.value) return
  try {
    vditor.value?.destroy?.()
  } catch (error) {
    console.log(error)
  }
  vditor.value = null
}

onMountedOrActivated(initVditor)

onBeforeUnmount(destroy)
onDeactivated(destroy)
</script>

<template>
  <div id="vditor"></div>
</template>
